import { Dialog } from "./dialog";

// 重试次数
let retryCount = 3;

export function request(
  opt: UniApp.RequestOptions | UniApp.UploadFileOption,
  type: "file" | "json" = "json"
): Promise<{ data: AnyObject; status: boolean }> {
  return new Promise((resolve, reject) => {
    if (type === "file") {
      opt = opt as UniApp.UploadFileOption;
      uni.uploadFile({
        url: opt.url,
        filePath: opt.filePath,
        file: opt.file,
        name: "file",
        success: (res: { data: string; }) => {
          const data = JSON.parse(res.data) as AnyObject;
          // 显示服务器返回的消息
          if (data.show == 1) {
            Dialog.alert(data.msg, () => {
              if (data.code == 200 || data.code == 1) {
                resolve({ data: data.data, status: true });
              } else {
                resolve({ data: data, status: false });
              }
            });
          } else {
            if (data.code == 200 || data.code == 1) {
              resolve({ data: data.data, status: true });
            } else {
              resolve({ data: data, status: false });
            }
          }
        },
        fail: (err: any) => {
          resolve({ data: err, status: false });
        },
      });
    } else {
      uni
        .request(opt as UniApp.RequestOptions)
        .then((res: { statusCode: number; data: { show: number; msg: string; code: number; data: any; }; }) => {
          if (res.statusCode == 200) {
            res.data = res.data as AnyObject;
            // 显示服务器返回的消息
            if (res.data.show == 1) {
              Dialog.alert(res.data.msg);
            }
            if (res.data.code == 200 || res.data.code == 1) {
              resolve({ data: res.data.data, status: true });
            } else {
              // #ifdef WEB
              if (res.data instanceof Blob) {
                resolve({
                  data: { file: res.data },
                  status: true,
                });
              } else {
                // 返回一个空对象，以免报错
                resolve({ data: res.data, status: false });
              }
              // #endif

              // #ifdef MP
              resolve({ data: res.data, status: false });
              // #endif
            }
          }
        })
        .catch((error: { response: { status: number; }; request: any; }) => {
          let errorMessage = "";
          if (error.response) {
            if (error.response.status >= 500) {
              errorMessage = "服务器遇到问题了，我们正在抓紧抢修中...";
            } else {
              errorMessage = "请求遇到一些问题了，我们正在抓紧抢修中...";
            }
          } else if (error.request) {
            if (!navigator.onLine) {
              errorMessage = "您当前网络已断开，请有网络时再尝试";
            } else {
              errorMessage = "您当前网络波动较大，连接超时";
            }
          } else {
            errorMessage = "请求失败，请稍后重试";
          }

          if (retryCount) {
            Dialog.confirm({
              text: errorMessage,
              confirmLabel: "重试",
              async confirmCallback() {
                await request(opt)
                  .then((res) => resolve(res))
                  .catch(() => reject());
              },
            });
            retryCount--;
          } else {
            Dialog.alert("重复次数太多，请稍后再试", () => reject());
            return;
          }
          reject();
        });
    }
  });
}
